import React from 'react';
import { Card, Space, Button, Form, Input, Table, Modal, Tag, message } from 'antd';
import dayjs from 'dayjs';

// 生成模拟数据（参照 Subscribe.vue 字段）
const mockRenewals = Array.from({ length: 24 }).map((_, i) => {
  const rentEquipment = Array.from({ length: (i % 3) + 1 }).map((__, j) => ({
    name: `设备${i}-${j}`,
    equipmentNo: `EQ-${String(1000 + i * 10 + j)}`,
    date: dayjs().add(j, 'month').format('YYYY-MM-DD')
  }));
  const stateLabels = ['Pending', 'Active', 'Canceled'];
  const stripeStates = ['active', 'trialing', 'past_due', 'canceled', 'incomplete', 'unpaid'];
  const payType = i % 2 === 0 ? 1 : 2; // 1月付/2年付
  return {
    stripeSubscriptionId: i % 5 === 0 ? '' : `sub_${String(20000 + i)}`,
    rentEquipment,
    state: stateLabels[i % stateLabels.length],
    stripeSubscriptionState: stripeStates[i % stripeStates.length],
    stripeSubscriptionPayType: payType,
  };
});

function StatusDot({ color = '#909399' }) {
  return <i style={{ display: 'inline-block', width: 8, height: 8, borderRadius: '50%', marginRight: 6, backgroundColor: color }} />;
}

export default function WalletSubscribe() {
  const [form] = Form.useForm();
  const [data, setData] = React.useState(mockRenewals.map(r => formatRecord(r)));
  const [filtered, setFiltered] = React.useState(data);
  const [deviceDialogVisible, setDeviceDialogVisible] = React.useState(false);
  const [deviceDialogList, setDeviceDialogList] = React.useState([]);
  const [instructionsVisible, setInstructionsVisible] = React.useState(false);

  function formatRecord(r) {
    const deviceCount = r.rentEquipment ? r.rentEquipment.length : 0;
    const deviceListIsView = deviceCount !== 1;
    const deviceList = deviceCount === 1 ? (r.rentEquipment[0].equipmentNo || '查看') : '查看';
    const statusLabel = r.state;
    const typeLabel = r.stripeSubscriptionPayType === 1 ? '月付' : '年付';
    const subscriptionStateLabel = r.stripeSubscriptionState || '';
    return {
      stripeSubscriptionId: r.stripeSubscriptionId || '',
      deviceCount,
      deviceList,
      deviceListIsView,
      statusLabel,
      subscriptionStateLabel,
      typeLabel,
      _raw: r,
    };
  }

  function statusColor(row) {
    const text = String(row.statusLabel || '').toLowerCase();
    if (text.includes('active') || text.includes('success') || text.includes('valid')) return '#52c41a';
    return '#ff4d4f';
  }

  function subscriptionStatusColor(row) {
    const raw = row._raw || {};
    const state = String(raw.stripeSubscriptionState || row.subscriptionStateLabel || '').toLowerCase();
    switch (state) {
      case 'active': return '#52c41a';
      case 'trialing': return '#1890ff';
      case 'past_due': return '#fa8c16';
      case 'canceled':
      case 'incomplete_expired': return '#909399';
      case 'incomplete':
      case 'unpaid': return '#ff4d4f';
      default: return '#909399';
    }
  }

  const columns = [
    {
      title: '订阅ID', dataIndex: 'stripeSubscriptionId', align: 'center', render: (v) => {
        const str = String(v || '').trim();
        return str.length ? str : '-';
      }
    },
    { title: '设备数量', dataIndex: 'deviceCount', align: 'center' },
    {
      title: '设备列表', dataIndex: 'deviceList', align: 'center', render: (text, row) => (
        <a onClick={() => viewDevices(row)}>{text}</a>
      )
    },
    {
      title: '订单状态', dataIndex: 'statusLabel', align: 'center', render: (text, row) => (
        <span style={{ display: 'inline-flex', alignItems: 'center' }}>
          <StatusDot color={statusColor(row)} />
          <span>{text}</span>
        </span>
      )
    },
    {
      title: '订阅状态', dataIndex: 'subscriptionStateLabel', align: 'center', render: (text, row) => (
        <span style={{ display: 'inline-flex', alignItems: 'center' }}>
          <StatusDot color={subscriptionStatusColor(row)} />
          <span>{text}</span>
        </span>
      )
    },
    { title: '类型', dataIndex: 'typeLabel', align: 'center' },
  ];

  function onSubmit() {
    const v = form.getFieldsValue();
    const next = data.filter(r => {
      const raw = r._raw || {};
      const matchSub = v.SubscriptionId ? (String(r.stripeSubscriptionId).includes(v.SubscriptionId)) : true;
      const matchName = v.machineName ? (raw.rentEquipment || []).some(eq => String(eq.name).includes(v.machineName)) : true;
      const matchNo = v.machineNo ? (raw.rentEquipment || []).some(eq => String(eq.equipmentNo).includes(v.machineNo)) : true;
      return matchSub && matchName && matchNo;
    });
    setFiltered(next);
  }

  function resetSearch() {
    form.resetFields();
    setFiltered(data);
  }

  function viewDevices(row) {
    const raw = row._raw || {};
    setDeviceDialogList(raw.rentEquipment || []);
    setDeviceDialogVisible(true);
  }

  async function handleStop() {
    // 模拟跳转 Stripe（示例）
    const newWin = window.open('', '_blank');
    const mockUrl = 'https://dashboard.stripe.com/test/customers';
    if (newWin) newWin.location.href = mockUrl; else window.location.href = mockUrl;
  }

  function handleAccountDeductions() {
    setInstructionsVisible(true);
  }

  return (
    <div className="wallet-subscribe">
      {/* 顶部操作与搜索 */}
      <Card variant="borderless" styles={{ body: { paddingTop: 8, paddingBottom: 8 } }}>
        <Space style={{ width: '100%', justifyContent: 'space-between' }}>
          <Space>
            <Button type="primary" onClick={handleAccountDeductions}>扣款说明</Button>
            <Button type="primary" onClick={handleStop}>Strip</Button>
          </Space>
          <Form form={form} layout="inline">
            <Form.Item name="SubscriptionId">
              <Input placeholder="订阅ID" allowClear style={{ width: 180 }} />
            </Form.Item>
            <Form.Item name="machineName">
              <Input placeholder="设备名称" allowClear style={{ width: 180 }} />
            </Form.Item>
            <Form.Item name="machineNo">
              <Input placeholder="设备编号" allowClear style={{ width: 180 }} />
            </Form.Item>
            <Form.Item>
              <Space>
                <Button type="primary" onClick={onSubmit}>查询</Button>
                <Button onClick={resetSearch}>重置</Button>
              </Space>
            </Form.Item>
          </Form>
        </Space>
      </Card>

      {/* 列表 */}
      <Card title="订阅记录" variant="borderless" styles={{ body: { paddingTop: 8 } }}>
        <Table
          rowKey={(r) => r.stripeSubscriptionId || `${Math.random()}`}
          dataSource={filtered}
          columns={columns}
          pagination={{ pageSize: 10 }}
        />
      </Card>

      {/* 设备列表弹窗 */}
      <Modal title="设备列表" open={deviceDialogVisible} onCancel={() => setDeviceDialogVisible(false)} footer={null} width={600}>
        <Table dataSource={deviceDialogList} rowKey={(r)=> r.equipmentNo} pagination={false} columns={[
          { title: '设备名称', dataIndex: 'name' },
          { title: '设备编号', dataIndex: 'equipmentNo' },
          { title: '到期时间', dataIndex: 'date' },
        ]} />
      </Modal>

      {/* 订阅说明弹窗 */}
      <Modal title="订阅说明" open={instructionsVisible} onOk={() => setInstructionsVisible(false)} onCancel={() => setInstructionsVisible(false)} width={640}>
        <div style={{ color: '#303133', fontSize: 14, lineHeight: 1.6 }}>
          <p><strong>检查未订阅设备</strong></p>
          <p>请确保需要订阅的设备尚未绑定订阅。</p>
          <p><strong>新设备与既有设备区别</strong></p>
          <p>新设备可能需要额外的认证或初始化步骤。</p>
          <p><strong>支付方式</strong></p>
          <p>可在客户门户中绑定银行卡进行订阅支付。</p>
          <p><strong>开始订阅</strong></p>
          <p>创建订阅后，系统会按周期自动扣费。</p>
          <p><strong>订阅支付</strong></p>
          <p>订阅支付失败时会显示为欠费或未完成状态。</p>
        </div>
      </Modal>
    </div>
  );
}